const App = getApp();
const db = wx.cloud.database();
const _ = db.command;
// 监听器
let watcher
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    InputBottom: 0,
    systemInfo: {},
    scrollId: '',
    //消息记录列表
    chatList: [],
    //标记触顶事件
    isTop: false,
    // input的输入信息
    content: '',
    // 消息类型
    msgType: "",
    // 照片
    fileList: [],
    // 班级id
    classId: null,
    // 讨论区id
    chatId: "",
    // 讨论区类型
    chatType: "",
    // 讨论区名称
    chatName: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    // 获取用户openid
    let getopenid = App.cache.getOpenID()
    // 获取用户信息
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    // 获取课程页面或者班级组件nav-lists传过来的班级号和名称
    let data = JSON.parse(decodeURIComponent(options.passData));
    console.log('传值过来的信息', data);
    that.setData({
      UserInfo: UserInfo,
      classId: data.myclassId,
      chatId: data.chatId,
      chatType: data.chatType,
      chatName: data.chatName,
      getopenid: getopenid,
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          systemInfo: res
        })
      }
    })
    App.toast.showLoading('获取聊天记录中')
    watcher = db.collection('chat-msg')
      .where(_.and([{
          ChatCommunityId: this.data.chatId
        },
        {
          chatType: this.data.chattype
        }
      ])).watch({
        onChange: this.onChange.bind(this),
        onError: function (err) {
          console.error(err)
        }
      })
    App.toast.hideLoading()
  },
  onChange(snapshot) {
    console.log('is init data', snapshot.type === 'init')
    console.log(snapshot);
    if (snapshot.type === 'init') {
      if (snapshot.docs.length === 0) {
        console.log('没有数据');
        return false
      }
      let list = snapshot.docs[0].records
      this.setData({
        chatList: [
          ...this.data.chatList,
          ...[...list].sort((x, y) => x.sendTimeTS - y.sendTimeTS)
        ],

      })
      let len = parseInt(this.data.chatList.length)
      this.setData({
        scrollId: 'y-' + parseInt(len - 1)
      })
    } else {
      for (const docChange of snapshot.docChanges) {
        // queueTyoe: 列表更新类型，表示更新事件对监听列表的影响
        switch (docChange.queueType) {
          case 'update':
            let list = docChange.doc.records
            let setchat = list[list.length - 1]
            console.log('更新了啥', setchat);
            let chatLtn = this.data.chatList.length
            this.setData({
              ['chatList[' + chatLtn + ']']: setchat
            })
            break
        }
      }
      let len = parseInt(this.data.chatList.length)
      // // 更新已读信息
      let chat_id = snapshot.docs[0]._id
      App.cache.setCache(chat_id, len)
      this.setData({
        scrollId: 'y-' + parseInt(len - 1)
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    watcher.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    App.toast.showToast('下拉 ！')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  InputFocus(e) {
    console.log('我看看', e);
    that.setData({
      InputBottom: e.detail.height
    })
  },
  InputBlur(e) {
    that.setData({
      InputBottom: 0
    })
  },
  // 消息输入
  bindKeyInput(event) {
    console.log(event.detail);
    that.setData({
      content: event.detail,
      msgType: "text"
    })
  },
  // 预览图片
  previewImage(e) {
    console.log('预览', e);
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: [url]
    })
  },


  selectImg() {
    let myFirstPromise = new Promise(function (resolve, reject) {
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        sizeType: ['compressed'],
        camera: 'back',
        success(res) {
          let imgpath = res.tempFiles[0].tempFilePath
          resolve(imgpath)
        }
      })
    });
    myFirstPromise.then(function (imgpath) {
      App.toast.showLoading('发送中')
      console.log('拿到吗', imgpath);
      let cloudPath = "class_msg_img/" + that.data.chatName + "/" + new Date().getTime() + ".png"
      wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: imgpath
      }).then(res => {
        console.log('拿到fileID', res.fileID)
        let show = false
        let msgType = 'image'
        //消息内容赋值
        const doc = {
          info: {
            openid: that.data.getopenid,
            nickName: that.data.UserInfo.nickName,
            account: that.data.UserInfo.account,
            avatarUrl: that.data.UserInfo.avatarUrl,
            identityId: that.data.UserInfo.identityId,
          },
          msgType: msgType,
          content: res.fileID,
          sendTime: App.Time.TimeCodeFine(),
          sendTimeTS: Date.now(),
          showTime: show
        }
        db.collection('chat-msg').where(_.and([{
            ChatCommunityId: that.data.chatId
          },
          {
            chatType: that.data.chattype
          }
        ])).update({
          data: {
            records: _.push(doc),
            latestNewsTime: Date.now(),
          },
          success: function (res) {
            App.toast.hideLoading()
          }
        })
      }).catch(error => {
        console.error(error);
      })
      App.toast.hideLoading()
    });


  },
  // 发送信息
  submit() {
    let show = false
    App.toast.showLoading('发送中')
    //消息内容赋值
    const doc = {
      info: {
        openid: that.data.getopenid,
        nickName: that.data.UserInfo.nickName,
        account: that.data.UserInfo.account,
        avatarUrl: that.data.UserInfo.avatarUrl,
        identityId: that.data.UserInfo.identityId,
      },
      msgType: that.data.msgType,
      content: that.data.content,
      sendTime: App.Time.TimeCodeFine(),
      sendTimeTS: Date.now(),
      showTime: show
    }
    db.collection('chat-msg').where(_.and([{
        ChatCommunityId: this.data.chatId
      },
      {
        chatType: this.data.chattype
      }
    ])).update({
      data: {
        records: _.push(doc),
        latestNewsTime: Date.now(),
      },
      success: function (res) {
        that.setData({
          content: ""
        })
      }
    })
    App.toast.hideLoading()
  },

  // 班级详情
  classRoute() {
    let classId = that.data.classId
    App.route.navTo('/pages/myclass/details/index', classId)
  }

})